package ldk.app.kotlinweibo.configs.dagger

import android.content.Context
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import ldk.app.kotlinweibo.apis.APIInterceptor
import ldk.app.kotlinweibo.configs.Session
import ldk.util.logger.LLog
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton

/**
 * The module for RootComponent
 * Created by yunjiao on 2017/6/15.
 */
@Singleton
@Module
class RootModule constructor(context: Context){
    private val mApplicationContext = context.applicationContext;

    internal lateinit var mSession: Session

    @Provides
    fun provideContext() = mApplicationContext

    @Provides @Singleton
    fun provideRetrofit(gson: Gson): Retrofit{
        val httpLoggingInterceptor = HttpLoggingInterceptor(
                HttpLoggingInterceptor.Logger {
                    message ->
                    LLog.v("HTTP", message)
                })
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val sinaAPIInterceptor = APIInterceptor(gson)
        val okHttpClient = OkHttpClient.Builder()
                .addInterceptor { interceptorSinaRequest(it) }
                .addInterceptor(sinaAPIInterceptor)
                .addInterceptor(httpLoggingInterceptor)
                .build()

        val retrofit = Retrofit.Builder().baseUrl("https://api.weibo.com/2/")
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        return retrofit
    }

    private inline fun interceptorSinaRequest(chain: Interceptor.Chain?): Response{
        var request = chain!!.request()
        val url = request.url().newBuilder()
                .addQueryParameter("access_token", mSession.sinaAccessToken()).build()
        request = request.newBuilder().url(url).build()
        return chain.proceed(request)
    }

    @Provides @Singleton
    fun provideGson(): Gson{
        return Gson()
    }
}